# Create your views here.
# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from myblog.post.models import Post
from taggle.models import Tag
from comment.forms import comment_form
from post.forms import Post_form
def all_posts(request):
    posts = Post.objects.all()
    user = request.user
    return render_to_response("post/post_all.html", locals())

def single(request, id):
    user = request.user
    post = Post.objects.get(id=id)
    comment = comment_form()
    return render_to_response("post/single.html", locals())

def created(request):
    user = request.user
    new_post = Post_form()
    return render_to_response("post/created.html", locals())

def save(request):
    user = request.user
    if request.method == "POST":
        form = Post_form(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            post = Post.objects.create(title=cd['title'], body=cd['content'], area = cd['area'], user = user)
            post.save
            tags = cd['tags'].split("|")
            for tag_item in tags:
                tag = Tag.objects.get_or_create(name=tag_item)
                tag[0].post.add(post)
            return HttpResponseRedirect('/')
        else:
            return HttpResponse(form.errors)

def delete(request, id):
    user = request.user
    if user.is_superuser:
        post = Post.objects.get(id=id)
        post.delete()
        return HttpResponseRedirect('/')
    else:
        return HttpResponse('权限不够')
    